import Base from './../model/base/Base.js'
export class afkeruCard extends Base {
  constructor () {
    super({
      name: 'ad[取]',
      dsc: '[取消息]',
      event: 'message',
      priority: -1,
      rule: [
        {
          reg: /^(#|\/)?\s*(取|取消息|拿|get)$/i,
          fnc: 'getMsg'
        }
      ]
    })
  }

  async getMsg (e) {
    if (!e.isMaster) return
    if (!e.source && !seq) {
      return e.reply('你尚未引用任何消息，获取消息失败')
    }
    let seq = e.source?.seq
    let source = e.isGroup
      ? (await e.group.getChatHistory(seq, 1)).pop()
      : (await e.friend.getChatHistory(seq, 1)).pop()
    if (source.user_id) {
      const userId = source.user_id || source.sender.user_id
      const username = source.sender.card || source.sender.nickname
      let msg = [
        '-------------------\ruser:\r-------------------',
        segment.image(`https://q1.qlogo.cn/g?b=qq&nk=${userId}&s=640`),
        `发送时间: ${toyyxx(new Date(source.time * 1000))}(${source.time})`,
        `message_id: ${source.message_id}`,
        `seq: ${source.seq}`,
        '-------------------\rmessage:\r-------------------'
      ]
      for (const item of source.parsed.message) {
        let data
        if (item.data) data = parseData(item.data)
        let jsonString = item
        if (jsonString.data) {
          try {
            jsonString.data = parseData(item.data) || item.data
          } catch {}
        }
        try {
          msg.push(JSON.stringify(jsonString, bufferToHexReplacer, 1))
        } catch {
          logger.info(jsonString)
          delete jsonString.size
          msg.push(JSON.stringify(jsonString, bufferToHexReplacer, 1))
        }
      }
      msg.push('---body---')
      source.parsed.message.forEach((i) => {
        msg.push(toProto(i))
      })
      const forward = msg.map((item) => ({
        user_id: userId,
        nickname: username,
        message: [item]
      }))
      const forwardMsg = e.isGroup
        ? await e.group.makeForwardMsg(forward)
        : await e.friend.makeForwardMsg(forward)
      return e.isGroup
        ? e.group.sendMsg(forwardMsg)
        : e.friend.sendMsg(forwardMsg)
    }
  }
}

function toyyxx (date) {
  const pad = (n) => (n < 10 ? '0' + n : n)
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(
    date.getDate()
  )} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(
    date.getSeconds()
  )}`
}

function parseData (data) {
  try {
    return JSON.parse(data)
  } catch (err) {
    return null
  }
}
function bufferToHexReplacer (key, value) {
  if (Buffer.isBuffer(value)) {
    return value.toString('hex')
  }
  if (typeof value === 'bigint') {
    return value.toString()
  }
  return value
}
function toProto (item) {
  const AT_BUF = Buffer.from([0, 1, 0, 0, 0])
  const BUF1 = Buffer.from([1])
  const BUF2 = Buffer.alloc(2)
  const bufMessage = Buffer.allocUnsafe(6)
  switch (item.type) {
    case 'text':
      return `{
 "1": {
  "1": "${item.text}"
 }
}`
    case 'image':
      return '这是一张图片'
    case 'at':
      bufMessage.writeUInt8(item.text.length)
      bufMessage.writeUInt8(1, 1)
      bufMessage.writeUInt32BE(0, 2)
      return `{
 "1": {
  "1": "${item.text}",
  "3": "${Buffer.concat([AT_BUF, bufMessage, BUF2]).toString('hex')}",
  "12": {
   "3": 2,
   "4": ${item.qq},
   "5": 0,
   "9": "${Bot.pickUser(item.qq).uid}",
   "11": 0
  }
 }
}`
    case 'raw':
      return '这是一个raw'
    default:
      break
  }
}
